﻿/*
 * Catalyst - http://catalystobjects.com
 * 
 * New BSD License (BSD)
 * 
 * Copyright (c) 2009, Ashley Brener
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 * 
 * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
 * 
 * Neither the name of Midlet Earth nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System;
using SubSonic;
using Catalyst.Caching;
using System.Data;
using System.Web.Caching;
using System.Web;
using System.Collections.Generic;

namespace Catalyst
{
	public class CachedDataLoader
	{
		public class DataRequest
		{
			public DataRequest(TableSchema.Table TableSchema)
				: this(TableSchema, null)
			{
			}

			public DataRequest(TableSchema.Table TableSchema, Dictionary<string, OrderByDirection> OrderBys)
			{
				this.TableSchema = TableSchema;
				this.OrderBys = OrderBys;
			}

			public TableSchema.Table TableSchema { get; set; }

			public Dictionary<string, OrderByDirection> OrderBys { get; set; }
		}

		public static List<T> GetCachedList<T>(DataRequest DataRequest)
			where T : IBusinessObject, new()
		{
			DataTable allData = GetCachedData(DataRequest);

			List<T> list = new List<T>();

			foreach (DataRow row in allData.Rows)
			{
				T businessObject = new T();
				businessObject.Load(DataRequest.TableSchema, row);
				list.Add(businessObject);
			}

			return list;
		}

		//public static ItemType GetCachedItem<ItemType>(DataRequest DataRequest, string ColumnName, object oVal)
		//    where ItemType : IBusinessObject, new()
		//{
		//    DataTable allData = getCachedData(DataRequest);

		//    foreach (DataRow row in allData.Rows)
		//    {
		//        if ()
		//    }

		//    ItemType item = new ItemType();

		//    item.Load(allData);

		//    return item;
		//}

		public static DataTable GetCachedData(DataRequest DataRequest)
		{
			bool loadFromCache = false;

			if (HttpContext.Current != null)
			{
				HashSet<string> cacheEnabledTables = new HashSet<string>(SqlCacheDependencyAdmin.GetTablesEnabledForNotifications(DataRequest.TableSchema.Provider.DefaultConnectionString));
				foreach (string enabledTable in cacheEnabledTables)
				{
					if (enabledTable == DataRequest.TableSchema.TableName)
					{
						loadFromCache = true;
						break;
					}
				}
			}

			if (loadFromCache)
			{
				DataTable allItems = CachingService.GetCachedObject<DataTable, DataRequest>(CachedDataLoader.GetCacheKey(DataRequest.TableSchema), new CachingService.ObjectLoader<DataTable, DataRequest>(CachedDataLoader.getAllCachedDataTable), new DataRequest[] { DataRequest });

				return Cloning.CloneHelper<DataTable>.Clone(allItems);
			}

			return getFreshData(DataRequest);
		}

		public static string GetCacheKey(TableSchema.Table TableSchema)
		{
			return String.Format("{0}_{1}", TableSchema.Provider.Name, TableSchema.Name);
		}

		private static CacheSettings<DataTable> getAllCachedDataTable(params DataRequest[] dataRequests)
		{
			DataRequest dataRequest = dataRequests[0];

			CacheSettings<DataTable> settings = new CacheSettings<DataTable>();

			SqlCacheDependency dependency = null;

			if (HttpContext.Current != null)
			{
				HashSet<string> cacheEnabledTables = new HashSet<string>(SqlCacheDependencyAdmin.GetTablesEnabledForNotifications(dataRequest.TableSchema.Provider.DefaultConnectionString));
				foreach (string enabledTable in cacheEnabledTables)
				{
					if (enabledTable == dataRequest.TableSchema.TableName)
					{
						dependency = new SqlCacheDependency(dataRequest.TableSchema.Provider.Name, enabledTable);
						break;
					}
				}
			}

			settings.CachedObject = getFreshData(dataRequest);
			settings.Dependency = dependency;

			return settings;
		}

		private static DataTable getFreshData(DataRequest dataRequest)
		{
			SqlQuery query = new Select().From(dataRequest.TableSchema);

			if (dataRequest.OrderBys != null && dataRequest.OrderBys.Count > 0)
			{
				foreach (KeyValuePair<string, OrderByDirection> orderBy in dataRequest.OrderBys)
				{
					switch (orderBy.Value)
					{
						case OrderByDirection.Desc: query.OrderDesc(orderBy.Key); break;
						default: query.OrderAsc(orderBy.Key); break;
					}
				}
			}

			return query.ExecuteDataSet().Tables[0];
		}
	}
}
